package com.icloud.common.web.aspect;

import com.icloud.common.core.api.CommonResult;
import com.icloud.common.web.util.I18nUtil;
import lombok.AllArgsConstructor;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;

@Aspect
@Component
@AllArgsConstructor
public class LanguageAspect {

    @Pointcut("execution(public com.icloud.common.core.api.CommonResult com.icloud..*.controller..*.*(..))")
    public void annotationLangCut() {

    }

    /**
     * 拦截controller层返回的结果，修改msg字段
     */
    @AfterReturning(pointcut = "annotationLangCut()", returning = "obj")
    public void afterReturning(JoinPoint point, Object obj) {
        CommonResult commonResult = (CommonResult) obj;
        try {
            String messageResult = I18nUtil.getMessageResult(commonResult.getMessage());
            if(commonResult.getArguments() != null && commonResult.getArguments().length > 0) {
                messageResult = MessageFormat.format(messageResult, commonResult.getArguments());
            }
            commonResult.setMessage(messageResult);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
